import { useState, useRef, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Popup, Input, PopupPosition  } from 'react-vant';
import Item from './Item';
import ChooseIcon from '@/assets/AiImgs/chooseIcon.png';
import SearchIcom from '@/assets/AiImgs/search.png';
import GrayArrow from '@/assets/AiImgs/hui-xia.png';
import BlackArrow from '@/assets/AiImgs/hei-xia.png';
import emptyImg from '@/assets/AiImgs/searchEmpty.png';
import trainEmptyImg from '@/assets/AiImgs/trainEmpty.png';
import { getTraiList, getOptions } from '@/api/train';

interface IProps {
  imgSrc?: string;
  text?: string;
  desc?: string;
}

const useDebounce = <T extends (...args: any[]) => any>(
  callback: T,
  delay: number
) => {
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  return useCallback((...args: Parameters<T>) => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
    
    timeoutRef.current = setTimeout(() => {
      callback(...args);
    }, delay);
  }, [callback, delay]);
};

const Empty = (props: IProps) => {
  const { imgSrc, text, desc } = props;
  return (
    <div className="text-center flex flex-col items-center">
      <img className="w-[180px] h-[180px] mt-[120px]" src={imgSrc} alt="empty" />
      <div className="text-base mb-2.5" style={{ fontFamily: 'PingFangTC-Semibold' }}>
        {text}
      </div>
      <div className="text-sm" style={{ fontFamily: 'PingFangSC-Light' }}>
        {desc}
      </div>
    </div>
  );
};

const PracticePage = () => {
  const [state, setState] = useState<PopupPosition>('');
  const [searchParams] = useSearchParams();
  const [activeFilter, setActiveFilter] = useState<number | null>(null);
  const [category1Options, setCategory1Options] = useState<any[]>([]);
  const [category2Options, setCategory2Options] = useState<any[]>([]);
  const [resultOptions, setResultOptions] = useState<any[]>([]);
  
  const trainingid = searchParams.get('trainingid');
  const title = searchParams.get('title');

  //@ts-ignore
  const decodedText = decodeURIComponent(title || '');
  
  const [filters, setFilters] = useState({
    category1Id: null as string | null,
    category2Id: null as string | null,
    resultId: null as string | null,
  });
  
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [records, setRecords] = useState<any[]>([]);
  
  const listRef = useRef<HTMLDivElement>(null);
  
  // 数据请求防抖处理
  const debouncedSearch = useDebounce((value: string) => {
    setSearchQuery(value);
    resetList();
  }, 500);
  
  // 重置列表和分页
  const resetList = () => {
    setCurrentPage(1);
    setRecords([]);
    setHasMore(true);
  };
  
  // 获取选项列表
  useEffect(() => {
    
    const fetchOptions = async () => {
      try {
        setSearchQuery(decodedText);
        const res = await getOptions();
        if (res.code === 2000) {
          setCategory1Options(res.data?.cate_list || []);
          
          // 展平二级分类选项
          const flatChildren = res.data?.cate_list?.flatMap(
            (item: any) => item.children || []
          ) || [];
          setCategory2Options(flatChildren);
          
          setResultOptions(res.data?.training_result_list || []);
        }
      } catch (error) {
        console.error('Failed to fetch options:', error);
      }
    };
    
    fetchOptions();

    
  }, []);
  
  // 获取训练记录
  useEffect(() => {
    const fetchRecords = async () => {
      if (isLoading || !hasMore) return;
      
      setIsLoading(true);
      
      try {
        const params: any = {
          page: currentPage,
          keywords: searchQuery,
        };
        
        if (trainingid) params.training_id = trainingid;
        if (filters.category1Id) params.first_category_id = filters.category1Id;
        if (filters.category2Id) params.second_category_id = filters.category2Id;
        if (filters.resultId) params.training_result = filters.resultId;
        
        const res = await getTraiList(params);
        
        if (res.code === 2000 && res.data) {
          const newRecords = [...records, ...(res.data.list || [])];
          setRecords(newRecords);
          setHasMore(newRecords.length < (res.data.total || 0));
        } else {
          setHasMore(false);
        }
      } catch (error) {
        console.error('Failed to fetch records:', error);
        setHasMore(false);
      } finally {
        setTimeout(() => {
          setIsLoading(false);
        }, 50);
      }
    };
    
    fetchRecords();
  }, [filters, searchQuery, currentPage]);
  
  // 滚动加载处理
  useEffect(() => {
    const element = listRef.current;
    if (!element) return;
    
    const handleScroll = () => {
      if (!element || isLoading || !hasMore) return;
      
      const { scrollTop, scrollHeight, clientHeight } = element;
      const isAtBottom = scrollTop + clientHeight >= scrollHeight - 50;
      
      if (isAtBottom) {
        setCurrentPage(prev => prev + 1);
      }
    };
    
    element.addEventListener('scroll', handleScroll);
    
    return () => {
      element.removeEventListener('scroll', handleScroll);
    };
  }, [isLoading, hasMore]);
  
  // 打开筛选弹窗
  const openFilterPopup = (filterType: number) => {
    setActiveFilter(filterType);
    setState('top');
  };
  
  // 关闭筛选弹窗
  const closeFilterPopup = () => {
    setState('');
    setActiveFilter(null);
  };
  
  // 应用筛选
  const applyFilter = (id: string) => {
    if (activeFilter === null) return;
    
    const newFilters = { ...filters };
    
    switch (activeFilter) {
      case 1: // 一级分类
        newFilters.category1Id = id;
        // 重置二级分类
        newFilters.category2Id = null;
        break;
      case 2: // 二级分类
        newFilters.category2Id = id;
        break;
      case 3: // 结果
        newFilters.resultId = id;
        break;
    }
    
    setFilters(newFilters);
    resetList();
    closeFilterPopup();
  };
  
  // 清除筛选
  const clearFilter = (filterType: number) => {
    const newFilters = { ...filters };
    
    switch (filterType) {
      case 1: // 一级分类
        newFilters.category1Id = null;
        // 重置二级分类
        newFilters.category2Id = null;
        break;
      case 2: // 二级分类
        newFilters.category2Id = null;
        break;
      case 3: // 结果
        newFilters.resultId = null;
        break;
    }
    
    setFilters(newFilters);
    resetList();
  };
  
  // 获取标签高亮标题
  const getHighlightedTitle = (text: string) => {
    if (!searchQuery.trim()) return text;
    
    const regex = new RegExp(
      `(${searchQuery.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`,
      'gi'
    );
    
    return text.replace(
      regex, 
      (match) => `<span style="color: #DB0007">${match}</span>`
    );
  };
  
  // 获取筛选标签文本
  const getFilterLabel = (filterType: number) => {
    let label = '';
    let list: any[] = [];
    
    switch (filterType) {
      case 1:
        label = '一级分类';
        list = category1Options;
        if (filters.category1Id) {
          return list.find(item => item.id === filters.category1Id)?.name || label;
        }
        break;
      case 2:
        label = '二级分类';
        list = category2Options;
        if (filters.category2Id) {
          return list.find(item => item.id === filters.category2Id)?.name || label;
        }
        break;
      case 3:
        label = '结果';
        list = resultOptions;
        if (filters.resultId) {
          return list.find(item => item.id === filters.resultId)?.name || label;
        }
        break;
    }
    
    return label;
  };
  
  // 判断是否有筛选条件
  const hasFilters = 
    filters.category1Id !== null || 
    filters.category2Id !== null || 
    filters.resultId !== null;
  
  // 是否有数据
  const hasRecords = records.length > 0;
  const showSearchEmpty = searchQuery && !isLoading && !hasRecords;
  const showFilterEmpty = !searchQuery && hasFilters && !isLoading && !hasRecords;
  
  // 是否显示筛选栏
  const showFilterBar = !showSearchEmpty || !showFilterEmpty;
  
  return (
    <div className="practicePage h-screen flex flex-col">
      {/* 搜索栏 */}
      <div className="bg-white sticky top-0 z-10">
        <div className="px-5 py-1.5">
          <Input
            value={searchQuery}
            className="px-3 searchStyle"
            onChange={(e: any) => debouncedSearch(e)}
            prefix={<img src={SearchIcom} className="w-5 h-5" />}
            clearable
            placeholder="搜索关键词"
          />
        </div>
        
        {/* 筛选栏 - 仅在非搜索空状态时显示 */}
        {showFilterBar && (
          <div className="flex px-5 py-2.5">
            {/* 一级分类筛选按钮 */}
            <FilterButton
              filterType={1}
              label={getFilterLabel(1)}
              isActive={filters.category1Id !== null}
              onClick={() => openFilterPopup(1)}
              onClear={() => clearFilter(1)}
            />
            
            {/* 二级分类筛选按钮 */}
            <FilterButton
              filterType={2}
              label={getFilterLabel(2)}
              isActive={filters.category2Id !== null}
              onClick={() => openFilterPopup(2)}
              onClear={() => clearFilter(2)}
            />
            
            {/* 结果筛选按钮 */}
            <FilterButton
              filterType={3}
              label={getFilterLabel(3)}
              isActive={filters.resultId !== null}
              onClick={() => openFilterPopup(3)}
              onClear={() => clearFilter(3)}
            />
          </div>
        )}
      </div>
      
      {/* 内容区域 */}
      <div
        ref={listRef}
        className="flex-1 overflow-y-auto bg-gray-50 pb-4"
      >
        {/* 空状态 - 搜索结果为空 */}
        {showSearchEmpty && (
          <div className="h-[86vh] flex flex-col justify-center items-center bg-white">
            <Empty
              imgSrc={emptyImg}
              text="无搜索结果"
              desc="请尝试输入其他关键词"
            />
          </div>
        )}
        
        {/* 空状态 - 筛选结果为空 */}
        {showFilterEmpty && (
          <div className="h-[86vh] flex flex-col justify-center items-center bg-white">
            <Empty
              imgSrc={trainEmptyImg}
              text="无训练记录"
              desc="请尝试其它筛选条件"
            />
          </div>
        )}
        
        {/* 记录列表 */}
        {hasRecords && (
          <div className="mx-4">
            {records.map((record, index) => (
              <Item
                key={`${record.id}-${index}`}
                data={{
                  ...record,
                  title: getHighlightedTitle(record.title)
                }}
              />
            ))}
            
            {/* 底部提示 */}
            <div className="text-center mb-4 mt-4">
              {isLoading ? (
                <div className="text-xs text-gray-400">加载中...</div>
              ) : hasMore ? (
                <div className="text-xs text-gray-400">上拉加载更多</div>
              ) : (
                <div className="text-xs text-gray-400">我是有底线的</div>
              )}
            </div>
          </div>
        )}
      </div>
      
      {/* 筛选弹窗 */}
      <Popup
        visible={state === 'top'}
        style={{ borderRadius: '0 0 20px 20px' }}
        position="top"
        onClose={closeFilterPopup}
      >
        <div className="bg-white">
          <div className="border-b border-gray-200">
            <div className="py-2.5 flex px-5">
              <FilterTab
                filterType={1}
                label="一级分类"
                isActive={activeFilter === 1}
                onClick={() => setActiveFilter(1)}
              />
              <FilterTab
                filterType={2}
                label="二级分类"
                isActive={activeFilter === 2}
                onClick={() => setActiveFilter(2)}
              />
              <FilterTab
                filterType={3}
                label="结果"
                isActive={activeFilter === 3}
                onClick={() => setActiveFilter(3)}
              />
            </div>
          </div>
          
          <div className="max-h-[60vh] overflow-y-auto">
            {(activeFilter === 1
              ? category1Options
              : activeFilter === 2
              ? category2Options
              : resultOptions
            ).map((option) => (
              <FilterOption
                key={option.id}
                id={option.id}
                name={option.name}
                isSelected={
                  (activeFilter === 1 && option.id === filters.category1Id) ||
                  (activeFilter === 2 && option.id === filters.category2Id) ||
                  (activeFilter === 3 && option.id === filters.resultId)
                }
                onClick={() => applyFilter(option.id)}
              />
            ))}
          </div>
        </div>
      </Popup>
    </div>
  );
};

// 筛选按钮组件
const FilterButton = ({
  filterType,
  label,
  isActive,
  onClick,
  onClear,
}: {
  filterType: number;
  label: string;
  isActive: boolean;
  onClick: () => void;
  onClear: () => void;
}) => {
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    
    // 如果已选中且有清除函数，则清除筛选
    if (isActive && onClear) {
      onClear();
    } else {
      onClick();
    }
  };
  
  return (
    <div
      className={`rounded-[18px] border-[0.5px] py-1 px-2.5 mr-2.5 text-xs cursor-pointer ${
        isActive
          ? 'border-[#FFBC0D] bg-[#FFF8E6] text-[#222222]'
          : 'border-[#dee2e6] text-[#666666]'
      }`}
      style={
        isActive ? { fontFamily: 'PingFangTC-Semibold' } : {}
      }
      onClick={handleClick}
    >
      {isActive && (
        <span 
          className="mr-1 text-[#DB0007] font-bold cursor-pointer"
          onClick={(e) => {
            e.stopPropagation();
            onClear();
          }}
        >
          × 
        </span>
      )}
      {label}
      <img 
        src={isActive ? BlackArrow : GrayArrow}
        className="inline-flex w-3 h-3 ml-1"
      />
    </div>
  );
};

// 筛选标签页组件
const FilterTab = ({
  filterType,
  label,
  isActive,
  onClick,
}: {
  filterType: number;
  label: string;
  isActive: boolean;
  onClick: () => void;
}) => (
  <div
    className={`rounded-[18px] border-[0.5px] py-1 px-2.5 mr-2.5 text-xs cursor-pointer ${
      isActive
        ? 'border-[#FFBC0D] bg-[#FFF8E6] text-[#222222] font-bold'
        : 'border-[#dee2e6] text-[#666666]'
    }`}
    onClick={onClick}
  >
    {label}
    <img 
      src={isActive ? BlackArrow : GrayArrow}
      className={`inline-flex w-3 h-3 ml-1 ${isActive ? 'rotate-180' : ''}`}
    />
  </div>
);

// 筛选选项组件
const FilterOption = ({
  id,
  name,
  isSelected,
  onClick,
}: {
  id: string;
  name: string;
  isSelected: boolean;
  onClick: () => void;
}) => (
  <div
    className={`pt-[23px] pb-[17px] pl-[24px] pr-[24px]  border-b border-[#00000014] text-base ${
      isSelected ? 'text-[#FFBC0D] font-semibold' : ''
    } last:border-0 cursor-pointer`}
    onClick={onClick}
  >
    <div className="flex justify-between">
      <div>{name}</div>
      {isSelected && <img src={ChooseIcon} className="w-6 h-6" />}
    </div>
  </div>
);

export default PracticePage;